<template>
	<view class="content">
		<!-- <view class="top-bar" @tap="toggleModel">
			<image v-if="displayModel==='map'"  class="icon-map" src="../../static/icons/list.png" mode="widthFix"></image>
			<image v-else class="icon-list" src="../../static/icons/map.png" mode="widthFix"></image>
			<text>{{displayModel !== 'list' ? '列表模式':'地图模式'}}</text>
		</view> -->
		<view class="task-header">
			<image src="../../static/image/indexBg.png" mode="aspectFill" class="bg"></image>
			<view class="cu-list menu padding-tb-sm">
				<view class="cu-item">
					<view class="content">
						<view class="text-bold">补液单号 BY202411271320</view>
						<view class="text-sm">2024-11-1 18:20:15！</view>
					</view>
					<view class="action"  @tap="toggleModel">
						<view class="cu-btn radius">地图查看
						<image src="../../static/image/mapIcon.png"/></view>
					</view>
				</view>
			</view>
			<view class="flex justify-between text-center">
				<view class="flex-sub">
					<view class="text-xxl">88.88</view>
					<view class="text-sm">补液总量(吨）</view>
				</view>
				<view class="flex-sub">
					<view class="text-xxl">88.88</view>
					<view class="text-sm">实际补液量（吨）</view>
				</view>
			</view>
		</view>
		<scroll-view class="task-list">
			<view class="cu-list menu padding-tb-sm margin-lr-sm radius" v-for="i in 5">
				<view class="cu-item">
					<view class="content">
						<view class="text-bold">撮镇路口加注机撮镇路口加注机1</view>
						<view class="text-sm">YZ001</view>
					</view>
				</view>
				<view class="addr padding-lr-sm ">地址：北京市大兴镇北京市大兴镇北京市大兴镇北京市大兴镇镇大兴镇121号</view>
				<view class="flex justify-between text-center padding-tb">
					<view class="flex-sub">
						<view class="text-xxl">88.88</view>
						<view class="text-sm">补液总量(吨）</view>
					</view>
					<view class="flex-sub">
						<view class="text-xxl">88.88</view>
						<view class="text-sm">实际补液量（吨）</view>
					</view>
				</view>
				<button class="cu-btn lg bg-blue block margin">完成补液</button>
				<button class="cu-btn lg block margin text-white">已完成</button>
			</view>
		</scroll-view>
		<template v-if="displayModel==='map'">
			<!-- 地图组件 -->
			<map
				id="theMap"
				style="width: 750rpx; height: 100vh;"
				show-location
				:latitude="latitude"
				:longitude="longitude"
				:markers="fsList"
				:scale="10"
				@markertap="markerTap"
				@regionchange="regionchange"
				@tap="clickMap"
			/>
		</template>

		<!-- 加注站列表 -->
		<!-- <scroll-view v-show="displayModel==='list'" class="fs-list" scroll-y>
			<view class="list">
				<view class="item">
					<view class="line-1 u-f-jsb">
						<view class="">
							<view class="name">撮镇路口加注机1</view>
							<view class="u-f-ac">
								<image class="icon" src="../../static/icons/location.png" mode="widthFix"></image>
								<text>地址：北京市大兴镇北京市大兴镇北京市大兴镇北京市大兴镇大兴镇121号</text>
							</view>
							<view class="u-f-ac">
								<image class="icon" src="../../static/icons/water.png" mode="widthFix"></image>
								<text>实际补液量66</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="list" v-for="(item, index) in originFslist" :key="item.siteId">
				<view class="item">
					<view class="line-1 u-f-jsb">
						<view class="">
							<view class="name">{{item.siteName}}</view>
							<view class="u-f-ac">
								<image class="icon" src="../../static/icons/location.png" mode="widthFix"></image>
								<text>{{item.siteAddress}}</text>
							</view>
							<view class="u-f-ac">
								<image class="icon" src="../../static/icons/task.png" mode="widthFix"></image>
								<text>补液任务 {{item.expectCapacity | kg2ton}}吨</text>
							</view>
							<view class="u-f-ac" v-if="item.actualCapacity">
								<image class="icon" src="../../static/icons/water.png" mode="widthFix"></image>
								<text>实际补液量 {{item.actualCapacity | kg2ton}}吨</text>
							</view>
						</view>
						<view @tap="openMap(item)">
							<image style="width: 100rpx;height: 100rpx;" src="../../static/icons/guide.png" mode="widthFix"></image>
							<view class="distance">{{item.distance}}km</view>
						</view>
					</view>
					<button class="btn" v-if="item.orderStatus === 2">已完成</button>
					<button class="btn active" v-if="item.orderStatus === 1" @tap="()=>readyReplenish(item.machineId, item.id)">开始补液</button>
					<button class="btn active" v-if="item.orderStatus === 4" @tap="()=>readyFinish(item.machineId, item.id)">完成补液</button>
				</view>
			</view>
		</scroll-view> -->
		
		<!-- 点击标记点后出现的信息弹窗 -->
		<view class="fs-info" v-show="markersInfoShow" @tap="openMap(fsInfo)">
			<view class="name text_over bg-blue text-white radius">{{ fsInfo.siteName }} sad
			<image class="icon" src="" mode="widthFix"></image> </view>
			<view class="padding-tb-xs padding-left-sm">yz001</view>
			<view class="brand padding-tb-xs padding-left-sm">{{ fsInfo.siteAddress }} </view>
			<view class="brand text_over text-df text-bold padding-left-sm">补液量(吨)： <text style="font-weight: bold;font-size: 30rpx;color: #407CFF;">{{fsInfo.expectCapacity | kg2ton}}</text></view>
		</view>
	
		
		<!-- 定位 -->
		<!-- <image
			src="../../static/wxImage/auto-position.png"
			v-show="displayModel==='map'"
			class="locate-btn"
			@tap="
				isClickLoca = true;
				getLocation();
			">
		</image> -->
		
		<u-popup v-model="showPopup" mode="center" :mask-close-able="false">
			<view class="popup-container">
				<view class="title">完成补液</view>
				<view class="input-wrapper">
					<view style="margin-bottom: 6rpx;">本次实际补液量：</view>
					<input focus type="digit" v-model="actualCapacity" />
					<text class="unit">吨</text>
				</view>
				<view class="btn-wrapper u-f-ac">
					<view @tap="closePopup">取消</view>
					<view @tap="finishPurchase">完成补液</view>
				</view>
			</view>
		</u-popup>
		<view class="cu-modal" :class="modalName=='finishing'?'show':''">
			<view class="cu-dialog bg-white tip">
				<view class="cu-bar bg-white justify-end">
					<view class="content text-bold">完成补液</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-black"></text>
					</view>
				</view>
				<view class="tip-content">
					<text>撮镇路口加注机1</text>
					<text class="text-bold">补液量(吨):99.99</text>
					<input focus type="digit" v-model="actualCapacity" />
				</view>
				<view class="flex justify-center padding-lg tip-btn">
					<button class="cu-btn bg-cancel margin-right-lg" @click="hideModal">取消</button>
					<button class="cu-btn bg-blue">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	components: {},
	data() {
		return {
			modalName:'finishing',
			showPopup: true,
			theMap: null, //地图map对象
			markerIndex: -1, //点击的标记点index
			markerWd: 28, //标记点icon宽度
			markerHe: 37, //标记点icon高度
			infoHeight: 1, //detail区域位置，1则在底部，2则在高处
			fsList: [], //加注站列表数组
			originFslist: [], // 加注站信息元数据
			fsInfo: {}, //加注站信息
			markersInfoShow: false, //是否显示marker信息
			touchStartY: 0, //信息区触摸上滑起始竖坐标
			latitudeDef: 0, //打开小程序时初始化的纬度，当用户移动距离超过200km时，将此字段进行更新
			longitudeDef: 0, //打开小程序时初始化的经度，当用户移动距离超过200km时，将此字段进行更新
			timer: null, //定时器，用于实时获取用户地理位置
			isOnShow: false, //是否为第二次以上打开此页面
			isClickLoca: false ,//是否点击定位按钮
			displayModel: 'list', // map--地图模式，list--列表模式
			actualCapacity: null,
			macInfo: null,
		};
	},
	computed: {
		//位置纬度
		latitude() {
			return this.$store.state.location.latitude;
		},
		//位置经度
		longitude() {
			return this.$store.state.location.longitude;
		},
		clientH() {
			return uni.getSystemInfoSync().windowHeight;
		}
	},
	
	onLoad(e) {
		this.orderId = e.orderId
	},
	// onShow() {
	// 	this.getLocation();
	// 	this.timer = setInterval(() => {
	// 		this.getLocation();
	// 	}, 120000);
	// },
	onReady() {
		//实例化组图map组件
		this.theMap = uni.createMapContext('theMap');
		// this.getLocation();
	},
	destroyed() {
		this.clearTimer();
	},
	methods: {
		openMap(item) {
			wx.openLocation({//​使用微信内置地图查看位置。
			  latitude: Number(item.latitude),//要去的纬度-地址
			  longitude: Number(item.longitude),//要去的经度-地址
			  name: item.siteName, 
			})
		},
		readyFinish(machineId,id) {
			this.id = id
			this.$http({
				url: this.$api.systemUrl + '/fillstorageorderdetail/viewBeforeCompleteMachineFill' ,
				contentType: 'json',
				data: {
					orderDetailId: id,
				},
				loading: 0
			}).then(res => {
				console.log('res',res);
				this.showPopup = true
				this.actualCapacity = res.data ? this.$operation(res.data.sensorChangeCapacity ,'/',1000) : ''
				// this.macInfo = res.data
				// if(this.macInfo.hasSensor === 1) {
				// 	// 有液位传感器
				// 	uni.showModal({
				// 		title:'提示',
				// 		content: '确认完成补液吗！',
				// 		success: (res) => {
				// 			if(res.confirm) {
				// 				this.finishPurchase()
				// 			}
				// 		}
				// 	})
				// } else {
					
				// }
			})
			
			
		},
		readyReplenish(machineId, id) {
			this.id = id
			this.$http({
				url: this.$api.systemUrl + 'fillmachine/detailById' ,
				method: 'get',
				data: {
					id: machineId,
				},
				loading: 0
			}).then(res => {
				this.macInfo = res.data
				if(this.macInfo.hasSensor) {
					// 有液位传感器
					this.startReplenish(id)
				} else {
					this.showPopup = true
				}
			})
		},
		startReplenish(id) {
			this.$http({
				url: this.$api.systemUrl + 'fillstorageorderdetail/startMachineFill' ,
				contentType: 'json',
				data: {
					orderDetailId: id,
					siteLat: this.latitude,
					siteLng: this.longitude
				},

				loading: 1
			}).then(res => {
				uni.showToast({
					title: '开始补液成功！'
				})
				this.getFillStatin()
			})
		},
		finishPurchase() {
			this.$http({
				url: this.$api.systemUrl + 'fillstorageorderdetail/completeMachineFill' ,
				contentType: 'json',
				data: {
					actualCapacity: this.actualCapacity * 1000 , 
					orderDetailId: this.id,
				},
				loading: 1
			}).then(res =>{
				uni.showToast({
					title: '补液完成',
				})
				this.id = null
				this.showPopup = true
				this.getFillStatin()
			})
		},
		closePopup() {
			this.showPopup = true
		},
		toggleModel() {
			this.displayModel = this.displayModel === 'map' ? 'list':'map'
		},
		//清除定时器
		clearTimer() {
			if (this.timer) clearInterval(this.timer);
		},
		//前往个人中心页
		goUser() {
			if(!this.isLogin) {
				return this.$store.commit('showLogin', true);
			}
			this.$navigateTo('/pagesUc/user/index');
		},
		//拨打电话
		callPhone(item, index) {
			if (item.contactPhone) {
				this.clearTimer();
				this.$callTel(item.contactPhone);
			}
		},
		//获取周围的加注站
		getFillStatin() {
			this.$http({
				url: this.$api.systemUrl + 'fillstorageorderdetail/listByOrderId/' + this.orderId,
				method: 'get',
				loading: 0
			}).then(res => {
				let arr = res.data;
				this.originFslist = JSON.parse(JSON.stringify(arr))
				arr.forEach((item, index) => {
					// item = this.convert2TecentMap(item);
					item._id = item.id
					item.id = index + 1
					item.width = this.markerWd;
					item.height = this.markerHe;
					item.latitude = parseFloat(item.siteLat);
					item.longitude = parseFloat(item.siteLng);
					// item.iconPath = '/static/icons/map-location.png';
					item.distance = this.$mapDistance(
						item.latitude,
						item.longitude,
						this.latitude,
						this.longitude
					);
					this.originFslist[index].distance = item.distance
				});
				this.fsList = arr
			});
		},
		//上拉/下拉detail
		setInfoHeight(idx) {
			if (idx === 1) {
				this.infoHeight = 2;
			} else {
				this.infoHeight = 1;
			}
			this.clickMap();
		},
		//点击地图，关闭信息框，缩小标记点等
		clickMap() {
			if (this.markerIndex >= 0) {
				this.fsList[this.markerIndex].width = this.markerWd;
				this.fsList[this.markerIndex].height = this.markerHe;
				this.markerIndex = -1;
			} else {
				this.markersInfoShow = false;
			}
		},
		//点击标记点
		markerTap(e) {
			let index = this.fsList.findIndex(item => item.id === e.markerId);
			//若是初次点击
			if (index !== this.markerIndex) {
				this.fsInfo = this.fsList[index];
				this.markersInfoShow = true;
				//先把点击点放大
				this.fsList[index].width = this.markerWd * 1.5;
				this.fsList[index].height = this.markerHe * 1.5;
				//再把现有变大的缩小
				if (this.markerIndex >= 0) {
					this.fsList[this.markerIndex].width = this.markerWd;
					this.fsList[this.markerIndex].height = this.markerHe;
				}
				//再重新赋值markerIndex
				this.markerIndex = index;
			}
			//若是重复点击
			else {
				this.clickMap();
			}
		},
		//地图视野变化，缩放或者移动
		regionchange(e) {
			if (e.type === 'begin') return;
			let {
				region: { northeast, southwest },
				centerLocation
			} = e.target;
			let distance1 = this.$mapDistance(
				northeast.latitude,
				northeast.longitude,
				this.latitudeDef,
				this.longitudeDef
			);
			let distance2 = this.$mapDistance(
				southwest.latitude,
				southwest.longitude,
				this.latitudeDef,
				this.longitudeDef
			);
			console.log(distance1, distance2);
			if (distance1 >= 200 || distance2 >= 200) {
				this.latitudeDef = centerLocation.latitude;
				this.longitudeDef = centerLocation.longitude;
				this.getFillStatin();
			}
		},
		//获取当前位置
		getLocation() {
			uni.getLocation({
				type: 'gcj02',
				success: res => {
					this.theMap.moveToLocation(); //将地图中心移动到当前定位点
					this.$store.commit('setLocation', res);
					this.clickMap();
					if (!this.isOnShow) {
						//初次打开页面(初始化)
						this.latitudeDef = res.latitude;
						this.longitudeDef = res.longitude;
						this.getFillStatin();
					} else {
						//再次回到这个页面
						let distance = this.$mapDistance(
							res.latitude,
							res.longitude,
							this.latitudeDef,
							this.longitudeDef
						);
						//当用户移动距离超过200km或者点击定位按钮时，更新相关数据
						if (distance >= 200 || this.isClickLoca) {
							this.latitudeDef = res.latitude;
							this.longitudeDef = res.longitude;
							if (this.isClickLoca) {
								this.isClickLoca = false;
							}
							this.getFillStatin();
						}
					}
				},
				fail: (e) => {
					console.log(e);
					if(e.errMsg.indexOf('频繁调用') !== -1) {
						// uni.showToast({
						// 	title:'定位太频繁了',
						// 	icon:'none'
						// })
						return
					};
					uni.showModal({
						content: '获取位置信息失败，请检查是否打开位置授权',
						showCancel: false,
						success: rs => {
							if (rs.confirm) {
								//#ifdef MP-WEIXIN
								wx.openSetting({});
								//#endif
							}
						}
					});
				}
			});
		},
		convert2TecentMap(obj) {
			if (obj.siteLng == '' && obj.siteLat == '') {
				return obj;
			}
			var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
			var x = obj.siteLng - 0.0065;
			var y = obj.siteLat - 0.006;
			var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
			var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
			var qqlng = z * Math.cos(theta);
			var qqlat = z * Math.sin(theta);
			obj.siteLng = qqlng;
			obj.siteLat = qqlat;
			return obj;
		}
	}
};
</script>

<style lang="scss">
/* 定位按钮 */
.task-header{
	position:relative;
	width:750rpx;
	height:297rpx;
	image.bg{
		width:710rpx;
		height:257rpx;
		position:absolute;
		left:20rpx;
		top:20rpx;
	}
	.cu-list{
		position:absolute;
		z-index:999;
		top:20rpx;
		left:20rpx;
		width:710rpx;
		.cu-item{
			background: none;
			color:#fff;
			&::after{
				border:0;
			}
		}
		.cu-btn{
			background: #18AE91;
			color:#fff;
		}
		image{
			width:40rpx;
			height:40rpx;
			margin-left:5rpx;
		}
	}
	.flex{
		position: absolute;
		top:150rpx;
		left:20rpx;
		width:710rpx;
		color:#fff;
	}
}
.task-list{
	.cu-list{
		background-color: #ffffff;
		.cu-item:after{
			border:0;
		}
		.text-sm{
			color:#7c7c7c;
		}
	}
}

.content {
	overflow: hidden;
}

// .top-bar {
// 	position: fixed;
// 	top: 0;
// 	width: 100vw;
// 	background: $color-primary;
// 	color: #FFFFFF;
// 	display: flex;
// 	justify-content: flex-end;
// 	align-items: center;
// 	height: 50rpx;
// 	z-index: 10;
// 	padding-bottom: 20rpx;
// 	padding-right: 20rpx;
	
// 	.icon-map {
// 		width: 36rpx;
// 		height: 36rpx;
// 		margin-right: 10rpx;
// 	}
	
// 	.icon-list {
// 		width: 24rpx;
// 		height: 22rpx;
// 		margin-right: 10rpx;
// 	}
// }

.locate-btn {
	position: fixed;
	right: 32rpx;
	bottom: 100rpx;
	width: 100rpx;
	height: 100rpx;
	z-index: $z-index-public;
}

// 扫码
.scan-wrapper {
	position: fixed;
	bottom: 10px;
	left: 50%;
	width: 320rpx;
	height: 88rpx;
	transform: translateX(-50%);
	background: linear-gradient(90deg, #1F72E5 0%, #4A95FD 100%);
	box-shadow: 0px 0px 12rpx rgba(146,146,146,0.7800);
	border-radius: 50rpx;
	
	.icon-scan {
		width: 40rpx;
		height: 40rpx;
		margin-right: 16rpx;
	}
	.text {
		font-size: 34rpx;
		color: #fff;
	}
}

// 加注站列表
.fs-list {
	width: 100%;
	margin-top: 60rpx;
	.list {
		padding: 30rpx;
		margin: 0 35rpx;
		margin-top: $spacing-col;
		box-shadow: $box-shadow;
		border-radius: $border-radius-bm;
		background: #fff;
		
		.item {
			.line-1 {
				.name {
					font-size: 36rpx;
					font-weight: bold;
					margin-bottom: 6rpx;
				}
				text {
					display: inline-block;
					font-size: 24rpx;
					color: #999999;
					margin-top: 10rpx;
				}
				
				.icon {
					margin-right: 6rpx;
					margin-top: 10rpx;
					width: 24rpx;
					height: 24rpx;
				}
			}
			
			
			.distance {
				text-align: center;
				font-weight: bold;
				font-size: 32rpx;
			}
			
			.btn {
				height: 88rpx;
				line-height: 88rpx;
				border-radius: 50rpx;
				margin-top: 20rpx;
				background: #DDDDDD;
				color: #666666;
				
				&.active {
					background: $color-primary;
					color: #FFFFFF;
				}
			}
		}
	}

	.list:last-child {
		margin-bottom: 200rpx;
	}
	
	
}

.fs-no-list {
	width: 100%;
	margin-top: 100rpx;
	text-align: center;
	color: $color-grey;
}

/* 点击标记点后出现的信息弹窗 */
.fs-info {
	position: fixed;
	top: 12%;
	left: 5%;
	width: 90%;
	padding: 0 0 30rpx;
	z-index: $z-index-public;
	background-color: $color-white;
	border-radius: $border-radius-sm;
	.name {
		font-size: 40rpx;
		line-height:80rpx;
		height:80rpx;
		padding-left:20rpx;
		image{
			float:right;
			width:28rpx;
			height:28rpx;
			margin-top:20rpx;
			margin-right:10rpx;
		}
	
	}	
	.brand {
		color: $color-grey-dark;
		margin-top: 16rpx;
		line-height:40rpx;
	}
	.icon {
		width: 30rpx;
		height: 30rpx;
		
	}
}

.model-switch {
	position: fixed;
	bottom: 200rpx;
	right: 40rpx;
	width: 80rpx;
	height: 160rpx;
	border-radius: 50rpx;
	background: #FFFFFF;
	box-shadow: 0rpx 0rpx 6rpx rgba(33,33,33,0.26);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	color: #212121;
	
	.text {
		width: 60rpx;
		font-size: 24rpx;
	}
	
	.icon-earth,.icon-list {
		width: 50rpx;
		height: 50rpx;
		margin-bottom: 8rpx;
	}
}
.popup-container {
	width: 570rpx;
	height: 380rpx;
	border-radius: 16rpx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: center;
	
	.title {
		text-align: center;
		line-height: 80rpx;
		margin-top: 10rpx;
	}
	
	.input-wrapper {
		position: relative;
		
		input {
			width: 440rpx;
			height: 45rpx;
			line-height: 45rpx;
			border: 1rpx solid #ccc;
			text-align: center;
			padding-right: 40rpx;
		}
		
		.unit {
			position: absolute;
			right: 20rpx;
			top: 50rpx;
		}
		
	}
	
	.btn-wrapper {
		border-top: 1px solid #eeeeee;
		height: 100rpx;
		width: 100%;
		
		>view {
			flex: 1;
			line-height: 100rpx;
			color: $color-primary;
			text-align: center;
			
			&:first-child {
				border-right: 1rpx solid #eeeeee;
			}
		}
	}
}
.u-drawer .u-mode-center-box {
	transform: translateY(-100rpx);
	border-radius: 16rpx;
}
.tip{
	input{
		background: #f5f5f5;
		height:90rpx;
		line-height: 90rpx;
		margin:0 20rpx;
	}
	.tip-content{
		.text-bold{
			font-size:28rpx;
		}
	}
}
</style>
